package com.xuhuan.juc.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author huan.xu
 * @Date 2021/12/29 22:24
 * @Description 读写锁案例：写的时候只能有一个线程写，写完了其他线程才能写，读的时候可以并发读。
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 1; i <= 5; i++) {
            int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp);
            }, "写" + i).start();
        }
        for (int i = 1; i <= 5; i++) {
            int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }, "读" + i).start();
        }
    }
}

@Slf4j
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            log.info("线程【{}】开始写入数据,key【{}】", Thread.currentThread().getName(), key);
            try {
                TimeUnit.MILLISECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.put(key, value);
            log.info("线程【{}】写入数据结束,写入值【{}】", Thread.currentThread().getName(), value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            log.info("线程【{}】开始读取数据,key【{}】", Thread.currentThread().getName(), key);
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Object resut = map.get(key);
            log.info("线程【{}】读取数据结束，结果【{}】", Thread.currentThread().getName(), resut);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}